package com.slink.xin.framework.inteceptor;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.slink.xin.framework.util.SessionUtil;

/**
 * 会话超时拦截器
 * @author 新
 *
 */
public class SessionInteceptor implements HandlerInterceptor {

	// 无需安全认证的url
    private List<String> excludeUrl = new ArrayList<String>();

    public boolean preHandle(HttpServletRequest request,
	    HttpServletResponse response, Object handler) throws Exception
    {
	HttpServletRequest r = (HttpServletRequest) request;
	String url = r.getRequestURI().replaceFirst(r.getContextPath(), "");

	for (int i = 0, len = this.excludeUrl.size(); i < len; i++)
	{
	    if (url.matches(this.excludeUrl.get(i)))
	    {
		return true;
	    }
	}

	Object memberInfo = SessionUtil.getMemberSession(request);
	if (memberInfo != null)
	{
	    return true;
	} else
	{
	    if (url.endsWith(".html"))
	    {
		response.sendRedirect(request.getContextPath()+"/index.html");
	    } else if (url.endsWith(".json"))
	    {
		try
		{
		    PrintWriter writer = response.getWriter();
		    response.setCharacterEncoding("UTF-8");
		    response.setContentType("text/plain; charset=utf-8");
		    Map<String, Object> map = new HashMap<String, Object>();
		    map.put("_code", "0101008");
		    map.put("_message", "str");
		    writer.write(new ObjectMapper().writeValueAsString(map));
		    writer.flush();
		} catch (Exception e)
		{
		    e.printStackTrace();
		}
	    }
	}

	return false;
    }

    public void postHandle(HttpServletRequest request,
	    HttpServletResponse response, Object handler,
	    ModelAndView modelAndView) throws Exception
    {

    }

    public void afterCompletion(HttpServletRequest request,
	    HttpServletResponse response, Object handler, Exception ex)
	    throws Exception
    {

    }

    public List<String> getExcludeUrl()
    {
	return excludeUrl;
    }

    public void setExcludeUrl(List<String> excludeUrl)
    {
	this.excludeUrl = excludeUrl;
    }

}
